package com.waimai1.waimai.exception;

import com.waimai1.waimai.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.io.IOException;
@Slf4j
@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public <T> R<T> exceptionHandler(Exception e) {
        if(e instanceof MaxUploadSizeExceededException){
            log.error(e.getMessage(),e);
            return R.err(703,"文件太大");
        }
        if(e instanceof MethodArgumentNotValidException){
            log.error(e.getMessage(),e);
            return R.err(702,e.getMessage());
        }
        if(e instanceof NotErrorException){
            log.error(e.getMessage(),e);
            return R.err(((NotErrorException) e).getCode(),e.getMessage());
        }
        if(e instanceof IOException){
            log.error(e.getMessage(),e);
            return R.err(701,"文件错误");
        }
        if(e instanceof NullPointerException){
            log.error(e.getMessage(),e);
            return R.err(702, "空指针错误");
        }
        log.error(e.getMessage(),e);
        return R.err(500,"服务器错误！");
    }

}
